package com.cloudweb.oa.controller;

import cn.js.fan.db.ListResult;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.web.DBInfo;
import cn.js.fan.web.Global;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.api.ICloudUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.Config;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.visual.FormDAO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

@RestController
@RequestMapping("/ide")
public class IdeController {

    @Autowired
    ICloudUtil cloudUtil;

    @Autowired
    HttpServletRequest request;

    @ApiOperation(value = "取数据源选项卡中的SQL语句及脚本库", notes = "取数据源选项卡中的SQL语句及脚本库", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dbSource", value = "数据源", dataType = "String"),
            @ApiImplicitParam(name = "table", value = "表名", dataType = "Arrray"),
    })
    @PostMapping(value="/getSqlsByDb", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getSqlsByDb(@RequestParam(value = "dbSource") String dbSource, @RequestParam(value = "dbSource") String table) {
        return new Result<>(getSqls(dbSource, table));
    }

    public JSONObject getSqls(String dbSource, String tableName) {
        String sql = "// 删除语句，请检查主键是否正确\r\n";
        sql += "sql = \"delete from " + tableName + " where id=?\";";
        JSONObject json = new JSONObject();
        json.put("sqlDelete", sql);

        sql = "select * from " + tableName;
        com.cloudwebsoft.framework.db.Connection conn = new com.cloudwebsoft.framework.db.Connection(dbSource);
        try {
            conn.setMaxRows(1); //尽量减少内存的使用
            ResultSet rs = conn.executeQuery(sql);
            ResultSetMetaData rm = rs.getMetaData();
            int colCount = rm.getColumnCount();
            String fields = "";
            for (int i = 1; i <= colCount; i++) {
                if ("".equals(fields)) {
                    fields = rm.getColumnName(i) + "=?";
                } else {
                    fields += ", " + rm.getColumnName(i) + "=?";
                }
            }
            sql = "// 修改语句，请检查主键是否正确\r\n";
            sql += "sql = \"update " + tableName + " set " + fields + " where id=?\";";
        } catch (SQLException e) {
            LogUtil.getLog(getClass()).error(e);
        } finally {
            conn.close();
        }
        json.put("sqlUpdate", sql);

        sql = "select * from " + tableName;
        conn = new com.cloudwebsoft.framework.db.Connection(dbSource);
        try {
            conn.setMaxRows(1); //尽量减少内存的使用
            ResultSet rs = conn.executeQuery(sql);
            ResultSetMetaData rm = rs.getMetaData();
            int colCount = rm.getColumnCount();
            String fields = "", token = "";
            for (int i = 1; i <= colCount; i++) {
                if ("".equals(fields)) {
                    fields = rm.getColumnName(i);
                    token = "?";
                } else {
                    fields += ", " + rm.getColumnName(i);
                    token += ", ?";
                }
            }
            sql = "sql = \"insert into " + tableName + " (" + fields + ") values (" + token + ")\";";
        } catch (SQLException e) {
            LogUtil.getLog(getClass()).error(e);
        } finally {
            conn.close();
        }
        json.put("sqlInsert", sql);

        sql = "select * from " + tableName;
        conn = new com.cloudwebsoft.framework.db.Connection(dbSource);
        try {
            conn.setMaxRows(1); //尽量减少内存的使用
            ResultSet rs = conn.executeQuery(sql);
            ResultSetMetaData rm = rs.getMetaData();
            int colCount = rm.getColumnCount();
            String fields = "";
            for (int i = 1; i <= colCount; i++) {
                if ("".equals(fields)) {
                    fields = rm.getColumnName(i);
                } else {
                    fields += ", " + rm.getColumnName(i);
                }
            }
            sql = "sql = \"select " + fields + " from " + tableName + "\";";
        } catch (SQLException e) {
            LogUtil.getLog(getClass()).error(e);
        } finally {
            conn.close();
        }
        json.put("sqlLoad", sql);
        return json;
    }

    @ApiOperation(value = "取表单选项卡中的SQL语句及脚本库", notes = "取数据源选项卡中的SQL语句及脚本库", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formCode", value = "表单编码", dataType = "String"),
    })
    @PostMapping(value="/getSqlsByFormCode", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getSqlsByFormCode(@RequestParam(value = "formCode") String formCode) {
        String table = FormDb.getTableName(formCode);
        return new Result<>(getSqls(Global.getDefaultDB(), table));
    }

    @ApiOperation(value = "取脚本模板列表", notes = "取脚本模板列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", dataType = "Integer"),
    })
    @PostMapping(value="/listTemplate", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> listTemplate(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize ) {
        // 脚本库
        JSONArray list = new JSONArray();
        String scriptFormCode = "script_template";
        String sql = "select id from " + FormDb.getTableName(scriptFormCode) + " order by id desc";
        com.redmoon.oa.visual.FormDAO fdao = new com.redmoon.oa.visual.FormDAO();
        ListResult lr = fdao.listResult(scriptFormCode, sql, page, pageSize);
        for (Object o : lr.getResult()) {
            FormDAO formDAO = (FormDAO)o;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", formDAO.getId());
            jsonObject.put("name", formDAO.getFieldValue("name"));
            list.add(jsonObject);
        }
        JSONObject json = new JSONObject();
        json.put("list", list);
        json.put("total", lr.getTotal());
        json.put("page", page);
        return new Result<>(json);
    }

    @ApiOperation(value = "取脚本模板的内容", notes = "取脚本模板的内容", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Long"),
    })
    @PostMapping(value="/getScriptTemplate", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getScriptTemplate(Long id) {
        FormDb fd = new FormDb();
        fd = fd.getFormDb("script_template");
        com.redmoon.oa.visual.FormDAO fdao = new com.redmoon.oa.visual.FormDAO();
        fdao = fdao.getFormDAO(id, fd);
        JSONObject json = new JSONObject();
        json.put("script", fdao.getFieldValue("script"));
        return new Result<>(json);
    }

    @ApiOperation(value = "取进入ide的登录地址", notes = "取进入ide的登录地址", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cwsToken", value = "cwsToken", dataType = "String"),
            @ApiImplicitParam(name = "formCode", value = "表单编码", dataType = "Arrray"),
    })
    @PostMapping(value="/getLoginCheckUrl", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getLoginCheckUrl(@RequestParam(value = "cwsToken", required = false) String cwsToken, @RequestParam(value = "formCode", required = false) String formCode) {
        com.redmoon.oa.Config cfg = Config.getInstance();
        String cloudUrl = "";
        if (cfg.getBooleanProperty("isCloud")) {
            cloudUrl = cloudUtil.getLoginCheckUrlForFront(cwsToken, formCode);
        }
        JSONObject json = new JSONObject();
        json.put("cloudUrl", cloudUrl);
        return new Result<>(json);
    }

    @ApiOperation(value = "取数据源", notes = "取数据源", httpMethod = "POST")
    @PostMapping(value="/getDbSources", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getDbSources() {
        JSONArray ary = new JSONArray();
        cn.js.fan.web.Config cfg = new cn.js.fan.web.Config();
        for (Object o : cfg.getDBInfos()) {
            DBInfo di = (DBInfo) o;
            JSONObject json = new JSONObject();
            json.put("name", di.name);
            json.put("isDefault", di.isDefault);
            ary.add(json);
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "根据数据源取表名", notes = "根据数据源取表名", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dbSource", value = "数据源", dataType = "String"),
    })
    @PostMapping(value="/getTables", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getTables(@RequestParam(value = "dbSource") String dbSource) {
        List<String> list = new ArrayList<>();
        JdbcTemplate jt = new JdbcTemplate(dbSource);
        for (Object o : jt.getTableNames()) {
            String tableName = (String) o;
            list.add(tableName);
        }
        return new Result<>(list);
    }

    @ApiOperation(value = "取表中的字段", notes = "取表中的字段", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dbSource", value = "数据源", dataType = "String"),
            @ApiImplicitParam(name = "table", value = "表名", dataType = "Arrray"),
    })
    @PostMapping(value="/getTableFields", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result<Object> getTableFields(@RequestParam(value = "dbSource") String dbSource, @RequestParam(value = "table") String table) {
        List<String> list = new ArrayList<>();
        String sql = "select * from " + table;
        com.cloudwebsoft.framework.db.Connection conn = new com.cloudwebsoft.framework.db.Connection(dbSource);
        try {
            conn.setMaxRows(1); //尽量减少内存的使用
            ResultSet rs = conn.executeQuery(sql);
            ResultSetMetaData rm = rs.getMetaData();
            int colCount = rm.getColumnCount();
            for (int i = 1; i <= colCount; i++) {
                list.add(rm.getColumnName(i));
            }
        } catch (SQLException e) {
            LogUtil.getLog(getClass()).error(e);
        } finally {
            conn.close();
        }
        return new Result<>(list);
    }
}
